from django.shortcuts import render
from django.http.response import JsonResponse, HttpResponse
from django.core import serializers

import json
from .models import *
# Create your views here.

def get_support_top_img(request):
    if request.method == "GET":
        db = SupportTopPicture.objects.last()
        return JsonResponse({"status": 0, "data": db.imgUrl.url, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})


def construct_newscard_dict(i):
    return {
        "uid": f"{i.id}",
        "title": i.title,
        "time": f"{i.create_date}",
        "detail": i.synopsis,
        "imgUrl": i.imgUrl.url,
        "content": i.content_render,
    }

def construct_videocard_dict(i):
    return {
        "uid": f"{i.id}",
        "title": i.title,
        "time": f"{i.create_date}",
        "imgUrl": i.imgUrl.url,
        "video_url": i.video_url,
    }

def construct_downloads_dict(i):
    return {
        "title": i.title,
        "time": f"{i.create_date}",
        "file_url": i.file_url,
    }


def get_newscard_all(request):
    if request.method == "GET":
        json_str = json.dumps([construct_newscard_dict(i) for i in SupportNews.objects.all()])
        return JsonResponse({"status": 0, "data": json_str, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})


def get_newscard(request):
    if request.method == "GET":
        uid = request.GET.get('uid')
        json_str = json.dumps(construct_newscard_dict(SupportNews.objects.get(id=uid)))
        return JsonResponse({"status": 0, "data": json_str, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})



def get_videocard_all(request):
    if request.method == "GET":
        json_str = json.dumps([construct_videocard_dict(i) for i in SupportVideos.objects.all()])
        return JsonResponse({"status": 0, "data": json_str, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})


def get_videocard(request):
    if request.method == "GET":
        uid = request.GET.get('uid')
        json_str = json.dumps(construct_videocard_dict(SupportVideos.objects.get(id=uid)))
        return JsonResponse({"status": 0, "data": json_str, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})



def get_downloads_all(request):
    if request.method == "GET":
        json_str = json.dumps([construct_downloads_dict(i) for i in SupportDownloads.objects.all()])
        return JsonResponse({"status": 0, "data": json_str, "message": "OK"})
    else:
        return JsonResponse({"status": 1, "data": None, "message": "Need Get Method"})